import base64
import hashlib
import hmac
import json
import time
from datetime import datetime
from data_center_data import get_data
import requests
from jinja2 import Template

# 读取HTML模板文件
with open('templates/jinja2_muban.html', 'r', encoding='utf-8') as file:
    html_template = file.read()
# 使用Jinja2模板引擎渲染HTML
template = Template(html_template)
rendered_html = template.render(get_data())
# 生成当前日期时间的字符串，作为文件名的一部分
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
output_html_filename = f"html/index_{timestamp}.html"  # 指定输出目录为 html

# 将生成的 HTML 保存到文件中
with open(output_html_filename, "w", encoding="utf-8") as output_file:
    output_file.write(rendered_html)



#---------------------推送到钉钉群---------------------------------
def send_to_dingtalk(webhook, secret, link_url):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')

    headers = {'Content-Type': 'application/json'}
    url = '{}&timestamp={}&sign={}'.format(webhook, timestamp, sign)

    # 发送链接消息
    link_data = {
        "msgtype": "link",
        "link": {
            "title": title,
            "text": "点击查看详情",
            "messageUrl": link_url
        }
    }

    response = requests.post(url=url, headers=headers, data=json.dumps(link_data))
    if response.status_code != 200:
        print("Failed to send message to DingTalk group.")
    else:
        print("Message sent to DingTalk group successfully.")


# 填入你的钉钉机器人的Webhook地址和加签密钥
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=a3339c727a445ee24fa076f03c3e1819674f972d5047bc42144b2e82b35c35bf'
#正式的webhook
#webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=94d7c12a420206291f346e2a98fec371ead181e3cc844d97b592af0d3116aafb'
link_url = f'http://x.x.x.x:9999/{output_html_filename}'  # 根据你的实际路径更新
#image_url = f'http://muyuan-dingding-image.oss-cn-shanghai.aliyuncs.com/datacenter/{path_date}/{output_img_filename}'
current_date = time.strftime("%Y-%m-%d", time.localtime())
title = '数据中心巡检任务-' + current_date
secret = 'sssssssssssssssssssss'

# 调用发送链接和图片到钉钉的函数
send_to_dingtalk(webhook_url, secret, link_url)